# -*- coding: utf-8 -*-
'''
Created on 2011-8-14

@author: zxz
'''
from datetime import datetime
import re,sys

from sqlalchemy.exc import IntegrityError
from flask import Flask, session, request

from datasource import db_session
from app import app
from userModel import User, UserInfo
from common.md5Util import md5
from common.jsonUtil import success, error

@app.route('/user/', methods=['GET'])
def user_test():
    ''' test '''
    u = db_session.query(User).filter(User.id == 1).first()
    # return 'dddd'
    return success({'user':'user test', 'u':u.entity()})

@app.route('/user/login/', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']
    print username, password
    if username is not None or password is not None :
        try :
            u = db_session.query(User).filter(User.email == username).filter(User.password == md5(password)).first()
        except :
            return error('600', u'something wrong')
        if u == None:
            return error('600', u'用户名或密码错误')
        else:
            session['UID'] = u.id
            return success({'UID':u.id})
    return error('600', u'输入有错')

@app.route('/user/register/', methods=['POST'])
def register():
    password = request.form['password']
    if password is None or len(password) < 4 or len(password) > 16:
        return error('600', u'密码长度在4－16之间')

    rpassword = request.form['rpassword']
    if rpassword != password:
        return error('600', u'2次输入密码不一致')

    email = request.form['email']
    if re.search(r'\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*', email) is None:
        return error('600', u'email错误')

    name = request.form['name']
    if name is None or len(name) < 2 or len(name) > 16:
        return error('600', u'姓名长度在2-16之间')

    try :
        register_u = User(email, u'', md5(password), datetime.now(), datetime.now())
        db_session.add(register_u)
        db_session.commit()

        userInfo = UserInfo(register_u.id, name, u'', u'',u'', u'')
        db_session.add(userInfo)
        db_session.commit()

        return success({'UID':register_u.id})
    except IntegrityError, e:
        db_session.rollback()
        print e
        return error('600',u'用户已经存在')
    except :
        db_session.rollback()
        print u'Unexpected error:', sys.exc_info()[0]
    return error('600', u'提交数据不合法')

@app.route('/user/logout/')
def logout():
    session.pop('UID', None)
    return success()

